package com.demo.service.impl;

import com.demo.common.Arith;
import com.demo.common.Constants;
import com.demo.common.OrderConstants;
import com.demo.dao.*;
import com.demo.entity.*;
import com.demo.service.*;
import com.demo.vo.OrderVo;
import com.demo.vo.SalePersonVolumeOfTrade;
import com.demo.wx.AdvancedUtil;
import com.demo.wx.Template;
import com.demo.wx.TemplateParam;
import com.demo.dao.*;
import com.demo.entity.*;
import com.demo.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Transactional
public class OrderServiceImpl implements IOrderService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IOrderDao dataDao;
    @Autowired
    private ISaleCommissionService saleCommissionService;
    @Autowired
    private ISaleCommissionDao saleCommissionDao;
    @Autowired
    private IOfferDao offerDao;
    @Autowired
    private IGoodsDao goodsDao;
    @Autowired
    private ISalePersonDao salePersonDao;
    @Autowired
    private ISaleLevelService saleLevelDao;
    @Autowired
    private ISalePersonAccountService spaService;
    @Autowired
    private OfferNumberDetailMapper ondService;
    @Autowired
    private UserWxMapper userWxDao;

    @Autowired
    private OrderPayDetailMapper opdDao;
    @Autowired
    private ILadingBillService lbService;

    @Autowired
    private IClienteleDao clienteleDao;
    @Autowired
    private ISalePersonAccountDao spaDao;
    /**
     * 订单合同
     */
    @Autowired
    private OrderPaperMapper opDao;

    public OrderServiceImpl() {
    }

    @Override
    public List<OrderVo> queryByPage(OrderVo user) {
        return dataDao.queryByPage(user);
    }

    @Override
    public List<OrderVo> queryByPage(OrderVo arg, List list) {
        return dataDao.queryByPage(arg, list);
    }

    @Override
    public int queryCount(OrderVo user, List list) {
        return dataDao.queryCount(user, list);
    }

    @Override
    public List<OrderVo> queryMyOrdersByPage(OrderVo user) {
        return dataDao.queryMyOrdersByPage(user);
    }

    @Override
    public List<OrderVo> queryMySalePersonOrdersByPage(OrderVo user) {
        return dataDao.queryMySalePersonOrdersByPage(user);
    }


    @Override
    public int deleteByPrimaryKey(Integer id) {
        return dataDao.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(Order record) {
        return dataDao.insert(record);
    }

    @Override
    public int insertSelective(Order record) {
        return dataDao.insertSelective(record);
    }

    @Override
    public Order selectByPrimaryKey(Integer id) {
        return dataDao.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(Order record) {
        return dataDao.updateByPrimaryKeySelective(record);
    }

    @Override
    public SalePersonVolumeOfTrade queryMyAccountSummary(SalePersonVolumeOfTrade spvot) {
        return dataDao.queryMyAccountSummary(spvot);
    }


    public Double judgeLevel(Double cashTotal) {
        List<SaleLevel> list = saleLevelDao.selectAll();
        Map<String, Double> map = new HashMap<String, Double>();

        for (SaleLevel sl : list) {
            map.put(String.valueOf(sl.getLevel()).trim(), sl.getPercent());
        }
        Double coefficient = 0.0;
        if (cashTotal < 500) {
            coefficient = map.get("500");
        } else if (cashTotal < 5000) {
            coefficient = map.get("5000");
        } else if (cashTotal < 20000) {
            coefficient = map.get("20000");
        } else if (cashTotal < 50000) {
            coefficient = map.get("50000");
        } else if (cashTotal < 100000) {
            coefficient = map.get("100000");
        } else if (cashTotal < 200000) {
            coefficient = map.get("200000");
        } else if (cashTotal < 400000) {
            coefficient = map.get("400000");
        } else if (cashTotal < 700000) {
            coefficient = map.get("700000");
        } else if (cashTotal < 1000000) {
            coefficient = map.get("1000000");
        }

        return coefficient;
    }


    /**
     * 订单审核
     *
     * @param arg
     * @return
     */
    @Override
    public Object checkOrder(Order arg) {
        if (arg.getCheckStatus().equals("1")) { //审核通过，为销售预发放佣金
            /***
             * 检查是否已经签订合同
             */
            if (arg.getId() == null) {
                return "参数非法!";
            }
            OrderPaper op = opDao.selectByOrderId(String.valueOf(arg.getId()));
            if (op == null) {
                return "该订单暂未保存合同，请先确定或上传合同!";
            }
            Order order = dataDao.selectByPrimaryKey(arg.getId());
            Offer offer = offerDao.selectByPrimaryKey(Integer.valueOf(order.getOfferId()));
            SalePerson sp = salePersonDao.selectByPrimaryKey(Integer.valueOf(order.getSaleId()));
            SaleCommission sc = new SaleCommission();
            sc.setOrderId(String.valueOf(arg.getId()));
            sc.setTotal(order.getActualTotal());
            sc.setSaleId(order.getSaleId());
            sc.setSaleName(order.getSaleName());
            sc.setNo(Constants.generateServiceNO("Y"));
            SalePersonAccount spa = spaService.selectBySaleId(String.valueOf(sp.getId()));
            String userID = sp.getUserId();
            List<SaleLevel> list = saleLevelDao.selectAll();
            Map<String, Double> map = new HashMap<String, Double>();
            if (userID != null && !"".equals(userID)) { // 新销售经理提成
                SalePerson spManger = salePersonDao.selectByPrimaryKey(Integer.valueOf(userID));
                SalePersonAccount spaManager = spaService.selectBySaleId(String.valueOf(spManger.getId()));
                SaleCommission scManger = new SaleCommission();
                scManger.setOrderId(String.valueOf(arg.getId()));
                scManger.setTotal(order.getTotal());
                scManger.setSaleId(order.getSaleId());
                scManger.setSaleName(order.getSaleName());
                scManger.setSaler(sp.getId().toString());
                scManger.setNo(Constants.generateServiceNO("Y"));
                scManger.setPercent(offer.getSalesManager());
                scManger.setCommission(Arith.mul(offer.getSalesManager() , order.getNumber()));
                scManger.setCommission(Arith.mul(judgeLevel(spaManager.getCashTotal()), scManger.getCommission()));
                spaManager.setCashWillReceiveTotal(Arith.add(spaManager.getCashWillReceiveTotal(), scManger.getCommission()));
                //佣金账户更新
                spaService.updateByPrimaryKeySelective(spaManager);
                //返佣明细登记
                saleCommissionDao.insertSelective(scManger);

                SalePerson salepManager = salePersonDao.selectByPrimaryKey(Integer.valueOf(userID));
                if (salepManager.getOpenid() != null) {
                    UserWx uwManager = new UserWx();
                    uwManager.setUnionid(salepManager.getOpenid());
                    uwManager.setUnitid(Constants.WXUserTypeWX);
                    UserWx ux1Manager = userWxDao.selectByUnionid(uwManager);
                    if (ux1Manager != null && ux1Manager.getOpenid() != null) { //系统包含微信账户
                        Template tem = new Template();
                        tem.setTemplateId(Constants.tmplReturnedCommission);
                        tem.setTopColor("#00DD00");
                        tem.setToUser(ux1Manager.getOpenid());
                        tem.setUrl(Constants.domain + "/wx/user/index.html");
                        List<TemplateParam> paras = new ArrayList<TemplateParam>();
                        paras.add(new TemplateParam("first", "您将获得销售员" + sp.getName() + "订单销售经理提成" + scManger.getCommission() + "元!", "#333333"));
                        paras.add(new TemplateParam("order", order.getNo(), "#333333"));
                        paras.add(new TemplateParam("money", String.valueOf(scManger.getCommission()), "#333333"));
                        paras.add(new TemplateParam("remark", "点击查看佣金账户及明细!", "#333333"));
                        tem.setTemplateParamList(paras);
                        AdvancedUtil.senderTmplSms(tem);
                    }
                }
            }
            sc.setPercent(offer.getSalesMan());
            sc.setCommission(offer.getSalesMan() * order.getNumber());
//            if (sp.getLevel().equals("0")) {

                //销售经理获取佣金
//            } else if (sp.getLevel().equals("1")) {
//                sc.setPercent(Arith.add(offer.getSalesManager(), offer.getSalesMan()));
//                sc.setCommission(sc.getPercent() * order.getNumber());
//            }

            for (SaleLevel sl : list) {
                map.put(String.valueOf(sl.getLevel()).trim(), sl.getPercent());
            }
            sc.setCommission(Arith.mul(judgeLevel(spa.getCashTotal()), sc.getCommission()));
            if (offer.getWithholdingNum() < order.getNumber()) {
                return "预售数量不足!";
            }
            //累加到销售佣金账户
            spa.setCashWillReceiveTotal(Arith.add(spa.getCashWillReceiveTotal(), sc.getCommission()));
            int count = saleCommissionDao.selectCountByOrderId(sc);
            if (count == 0) {
                //佣金账户更新
                spaService.updateByPrimaryKeySelective(spa);
                //返佣明细登记
                saleCommissionDao.insertSelective(sc);
            }
            //报价中预扣订单数量
            OfferNumberDetail ond = new OfferNumberDetail();
            ond.setNo(Constants.generateServiceNO("OT"));
            ond.setOfferId(String.valueOf(offer.getId()));
            ond.setOrderId(String.valueOf(arg.getId()));
            ond.setNumber(order.getNumber());
            ond.setType("0");
            ondService.insertSelective(ond);
            //扣除报价中预售数量，增加已售就数量
//            offer.setWithholdingNum(Arith.sub(offer.getWithholdingNum(), order.getNumber()));
//            offer.setDeductedNum(Arith.add(offer.getDeductedNum(), order.getNumber()));
//            offerDao.updateByPrimaryKeySelective(offer);

            SalePerson salep = salePersonDao.selectByPrimaryKey(Integer.valueOf(order.getSaleId()));
            if (salep.getOpenid() != null) {
                UserWx uw = new UserWx();
                uw.setUnionid(salep.getOpenid());
                uw.setUnitid(Constants.WXUserTypeWX);
                UserWx ux1 = userWxDao.selectByUnionid(uw);
                if (ux1 != null && ux1.getOpenid() != null) { //系统包含微信账户
                    Template tem = new Template();
                    tem.setTemplateId(Constants.tmplUpdateOrderStatus);
                    tem.setTopColor("#00DD00");
                    tem.setToUser(ux1.getOpenid());
                    tem.setUrl(Constants.domain + "/wx/user/order.html");

                    List<TemplateParam> paras = new ArrayList<TemplateParam>();
                    paras.add(new TemplateParam("first", "您的订单审核成功，本订单将获得佣金" + sc.getCommission() + "元!", "#333333"));
                    paras.add(new TemplateParam("OrderSn", order.getNo(), "#333333"));
                    paras.add(new TemplateParam("OrderStatus", "审核成功", "#333333"));
//                    paras.add(new TemplateParam("backupFieldName", "报价名称：", "#666666"));
//                    paras.add(new TemplateParam("backupFieldData", order.getGoodsName(), "#666666"));
                    paras.add(new TemplateParam("remark", "感谢您对我们的支持!!!", "#333333"));
//                    tmplReturnedCommission
                    tem.setTemplateParamList(paras);
                    AdvancedUtil.senderTmplSms(tem);
                }
            }
        } else if (arg.getCheckStatus().equals("2")) { //审核未通过
            Order order = dataDao.selectByPrimaryKey(arg.getId());
            SalePerson salep = salePersonDao.selectByPrimaryKey(Integer.valueOf(order.getSaleId()));

            if (salep.getOpenid() != null) {
                UserWx uw = new UserWx();
                uw.setUnionid(salep.getOpenid());
                uw.setUnitid(Constants.WXUserTypeWX);
                UserWx ux1 = userWxDao.selectByUnionid(uw);
                if (ux1 != null && ux1.getOpenid() != null) { //系统包含微信账户

                    Template tem = new Template();
                    tem.setTemplateId(Constants.tmplUpdateOrderStatus);
                    tem.setTopColor("#00DD00");
                    tem.setToUser(ux1.getOpenid());
                    tem.setUrl(Constants.domain + "/wx/user/order.html");

                    List<TemplateParam> paras = new ArrayList<TemplateParam>();
                    paras.add(new TemplateParam("first", "您的订单审核未通过，原因" + arg.getReason() + "!如有疑问，请登录查询。 ", "#FF3333"));
                    paras.add(new TemplateParam("OrderSn", order.getNo(), "#333333"));
                    paras.add(new TemplateParam("OrderStatus", "未通过", "#333333"));
//                    paras.add(new TemplateParam("backupFieldName", "报价名称：", "#333333"));
//                    paras.add(new TemplateParam("backupFieldData", order.getGoodsName(), "#333333"));
                    paras.add(new TemplateParam("remark", "感谢您对我们的支持!!!", "#333333"));

                    tem.setTemplateParamList(paras);
                    AdvancedUtil.senderTmplSms(tem);
                }
            }
            Offer offer = offerDao.selectByPrimaryKey(Integer.valueOf(order.getOfferId()));
            //扣除报价中预售数量，增加已售就数量
            offer.setSaleNum(Arith.add(offer.getSaleNum(), order.getNumber()));
            offer.setWithholdingNum(Arith.sub(offer.getWithholdingNum(), order.getNumber()));
            offerDao.updateByPrimaryKeySelective(offer);
        }
        return dataDao.updateByPrimaryKeySelective(arg);
    }

    /**
     * 更新订单实际成交价格
     *
     * @param arg
     * @return
     */
    @Override
    public Object updatePrice(Order arg) {
        Order order = dataDao.selectByPrimaryKey(arg.getId());
        if ("1".equals(order.getCheckStatus())) {
            return "订单已经审核,无法修改!";
        }
        if ("1".equals(order.getPayStatus())) {
            return "订单已经付款,无法修改!";
        }
        arg.setActualTotal(Arith.mul(arg.getActualPrice(), order.getNumber()));
        int res = dataDao.updateByPrimaryKeySelective(arg);
        if (res > 0) { // tmpl msg notice
            SalePerson salep = salePersonDao.selectByPrimaryKey(Integer.valueOf(order.getSaleId()));
            if (salep.getOpenid() != null) {
                UserWx uw = new UserWx();
                uw.setUnionid(salep.getOpenid());
                uw.setUnitid(Constants.WXUserTypeWX);
                UserWx ux1 = userWxDao.selectByUnionid(uw);
                if (ux1 != null) {
                    Template tem = new Template();
                    tem.setTemplateId(Constants.tmplUpdateOrderPrice);
                    tem.setTopColor("#00DD00");
                    tem.setToUser(ux1.getOpenid());
                    tem.setUrl(Constants.domain + "/wx/user/order.html");
                    List<TemplateParam> paras = new ArrayList<TemplateParam>();
                    paras.add(new TemplateParam("first", "您好，你购买的商品价格已被卖家调整，请去我的订单进行支付。", "#333333"));
                    paras.add(new TemplateParam("orderID", order.getNo(), "#666666"));
                    paras.add(new TemplateParam("keyword2", order.getPrice().toString(), "#666666"));
                    paras.add(new TemplateParam("keyword3", arg.getActualPrice().toString(), "#666666"));
                    paras.add(new TemplateParam("backupFieldData", arg.getGoodsName(), "#666666"));
                    paras.add(new TemplateParam("remark", "请注意价格调整!", "#666666"));
                    tem.setTemplateParamList(paras);
                    AdvancedUtil.senderTmplSms(tem);
                }
            }
        }
        return res;
    }

    /**
     * 销售下单
     *
     * @param arg
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Object create(Order arg) {
        try {
//          clientele
            Clientele clientele = clienteleDao.selectByPrimaryKey(Integer.valueOf(arg.getClienteleId()));
            arg.setClienteleName(clientele.getComName());
            arg.setClienteleUserName(clientele.getPerson());
            arg.setClienteleUserPhone(clientele.getPhone());
            //goods
            Goods goods = goodsDao.selectByPrimaryKey(Integer.valueOf(arg.getGoodsId()));
            arg.setGoodsName(goods.getName());
//          offer
            Offer offer = offerDao.selectByPrimaryKey(Integer.valueOf(arg.getOfferId()));
            arg.setActualPrice(offer.getPrice());
            arg.setPrice(offer.getPrice());
            arg.setTotal(Arith.mul(offer.getPrice(), arg.getNumber()));
            arg.setActualTotal(arg.getTotal());
            if (arg.getNumber() > offer.getSaleNum()) {
                return "库存不足,不能完成下单!";
            }
            arg.setNo(Constants.generateServiceNO("X", Constants.generateLimitNumberStr(dataDao.queryCurrentMonthCount() + 1, 5)));

            Integer service_res = dataDao.insertSelective(arg);
            if (service_res.equals(1)) {
                //可售数量预扣
                Offer offer_update = new Offer();
                offer_update.setId(offer.getId());
                offer_update.setSaleNum(Arith.sub(offer.getSaleNum(), arg.getNumber()));
                offer_update.setWithholdingNum(Arith.add(offer.getWithholdingNum(), arg.getNumber()));
                offer_update.setCount(offer.getCount() == null ? 0 : offer.getCount() + 1);
                offerDao.updateByPrimaryKeySelective(offer_update);

                Goods g = new Goods();
                g.setId(goods.getId());
                if (g.getCount() == null) {
                    g.setCount(1);
                } else {
                    g.setCount(g.getCount() + 1);
                }
                goodsDao.updateByPrimaryKeySelective(g);
                SalePerson salep = salePersonDao.selectByPrimaryKey(Integer.valueOf(arg.getSaleId()));
                if (salep.getOpenid() != null) {
                    UserWx uw = new UserWx();
                    uw.setUnionid(salep.getOpenid());
                    uw.setUnitid(Constants.WXUserTypeWX);
                    UserWx ux1 = userWxDao.selectByUnionid(uw);
                    if (ux1 != null && ux1.getOpenid() != null) { //系统包含微信账户
                        Template tem = new Template();
                        tem.setTemplateId(Constants.tmplCreateOrder);
                        tem.setTopColor("#00DD00");
                        tem.setToUser(ux1.getOpenid());
                        tem.setUrl(Constants.domain + "/wx/user/order.html");
                        List<TemplateParam> paras = new ArrayList<TemplateParam>();
                        paras.add(new TemplateParam("first", "您的订单已提交成功,目前已进入审核阶段，工作人员将与您电话联系，请保持电话畅通。 ", "#333333"));
                        paras.add(new TemplateParam("orderID", arg.getNo(), "#666666"));
                        paras.add(new TemplateParam("orderMoneySum", arg.getActualTotal().toString(), "#666666"));
                        paras.add(new TemplateParam("backupFieldName", "报价名称：", "#666666"));
                        paras.add(new TemplateParam("backupFieldData", arg.getGoodsName(), "#666666"));
                        paras.add(new TemplateParam("Remark", "感谢您对我们的支持!!!", "#666666"));

                        tem.setTemplateParamList(paras);
                        AdvancedUtil.senderTmplSms(tem);
                    }
                }
            }
            return service_res;
        } catch (Exception e) {
            logger.error("[创建订单异常----]" + e.getStackTrace());
            logger.debug("[创建订单异常----]" + e.getMessage());
            return "服务端异常!";
        }
    }

    /**
     * 强制执行完毕订单时的佣金发放
     *
     * @param orderId
     */
    public void giveActualCommissionForForceEnd(String orderId) {
        SaleCommission sc = new SaleCommission();
        sc.setOrderId(orderId);
        SaleCommission sc_res = saleCommissionDao.selectOneByOrderId(sc);
        if (sc_res != null) {
            sc_res.setStatus("1"); //1入账
            SalePersonAccount spa = new SalePersonAccount();
            SalePersonAccount spa_res = spaDao.selectBySaleID(sc_res.getSaleId());
            spa_res.setCashWillReceiveTotal(Arith.sub(spa_res.getCashWillReceiveTotal(), sc_res.getCommission()));
            spa_res.setCashCanWithDrawTotal(Arith.add(spa_res.getCashCanWithDrawTotal(), sc_res.getCommission()));
            spaDao.updateByPrimaryKeySelective(spa_res);
            saleCommissionDao.updateByPrimaryKeySelective(sc_res);
            // todo：入账模板消息通知：强制执行完毕

        }
    }

    /**
     * 强制执行完毕
     * 1. 发放佣金
     * 2. 更新报价相关数据
     * 3. 更新订单相关数据
     * 4. 更新提单相关数据
     *
     * @param arg
     * @return
     */
    @Override
    public Object forceEnd(Order arg) {
        Order order = dataDao.selectByPrimaryKey(arg.getId());
        if ("0".equals(order.getCheckStatus())) {
            return "订单未审核!";
        }
        if (!"1".equals(arg.getStatus())) {
            if (!"1".equals(order.getPayStatus())) {
                return "订单未付款!";
            }
        }
        SalePerson sp = salePersonDao.selectByPrimaryKey(Integer.valueOf(order.getSaleId()));
        SaleCommission scQuery = new SaleCommission();
        scQuery.setOrderId(String.valueOf(order.getId()));
        scQuery.setSaleId(order.getSaleId());
        SaleCommission sc = saleCommissionDao.selectOneByOrderId(scQuery);
        if (sc == null) {
            return "订单没有销售佣金数据!";
        }
        Offer offer = offerDao.selectByPrimaryKey(Integer.valueOf(order.getOfferId()));
        Offer countOrder = new Offer();
        countOrder.setId(offer.getId());
        Double remain = Arith.sub(order.getNumber(), order.getActualNumber());
        if (remain > 0) {
            //todo:报价相关数据
            countOrder.setWithholdingNum(Arith.sub(offer.getWithholdingNum(), order.getNumber()));//报价中预扣除数量-剩余订单数量
            countOrder.setDeductedNum(Arith.add(offer.getDeductedNum(), order.getActualNumber())); //报价中已经扣除数量+剩余订单数量
            countOrder.setSaleNum(Arith.add(offer.getSaleNum(), remain)); //报价中已经扣除数量+剩余订单数量
            if (order.getNumber().equals(remain)) {
                countOrder.setCount(offer.getCount() - 1);
            }
            offerDao.updateByPrimaryKeySelective(countOrder); //订单成交数量+1
        }

        arg.setActualTotal(Arith.mul(order.getActualNumber(), order.getActualPrice()));
        // 提货单相关数据
        int res_order = dataDao.updateByPrimaryKeySelective(arg);
        if (res_order > 0) {
            SaleCommission sc_ = new SaleCommission();
            sc_.setSaleId(order.getSaleId());
            sc_.setOrderId(order.getId().toString());
            saleCommissionService.giveCommission(sc_);
        }
        return res_order;
    }

    @Override
    public Object endOrder(Order arg) {
        Order order = dataDao.selectByPrimaryKey(arg.getId());
        if ("0".equals(order.getCheckStatus())) {
            return "订单未审核!";
        }


//
//        SalePerson sp = salePersonDao.selectByPrimaryKey(Integer.valueOf(order.getSaleId()));
//        SaleCommission scQuery = new SaleCommission();
//        scQuery.setOrderId(String.valueOf(order.getId()));
//        scQuery.setSaleId(order.getSaleId());
//        SaleCommission sc = saleCommissionDao.selectOneByOrderId(scQuery);
//        if (sc == null) {
//            return "订单没有销售佣金数据!";
//        }
//        Offer offer = offerDao.selectByPrimaryKey(Integer.valueOf(order.getOfferId()));
//        Offer countOrder = new Offer();
//        countOrder.setId(offer.getId());
//        Double remain = Arith.sub(order.getNumber(), order.getActualNumber());
//        if (remain > 0) {
//            //todo:报价相关数据
//            countOrder.setWithholdingNum(Arith.sub(offer.getWithholdingNum(), order.getNumber()));//报价中预扣除数量-剩余订单数量
//            countOrder.setDeductedNum(Arith.add(offer.getDeductedNum(), order.getActualNumber())); //报价中已经扣除数量+剩余订单数量
//            countOrder.setSaleNum(Arith.add(offer.getSaleNum(), remain)); //报价中已经扣除数量+剩余订单数量
//            offerDao.updateByPrimaryKeySelective(countOrder); //订单成交数量+1
//        }
//        //订单相关数据
//        arg.setDeliverStatus("1");//订单状态 ->完全发货
//        arg.setActualTotal(Arith.mul(order.getDeliverNumber(), order.getActualPrice()));
//        // 提货单相关数据
//        int res_order = dataDao.updateByPrimaryKeySelective(arg);
//        if (res_order > 0) {
//            SaleCommission sc_ = new SaleCommission();
//            sc_.setSaleId(order.getSaleId());
//            sc_.setOrderId(order.getId().toString());
//            saleCommissionService.giveCommission(sc_);
//        }
        return dataDao.updateByPrimaryKeySelective(arg);
    }

    @Override
    public Object payed(Order arg) {
        OrderPayDetail opd = new OrderPayDetail();
        opd.setActualTotal(arg.getActualTotal());
        opd.setOrderId(String.valueOf(arg.getId()));
        opd.setOperator(arg.getOfferId()); //OfferId穿过登录用户ID
        opdDao.insertSelective(opd);
        arg.setOfferId(null);
        return dataDao.updateByPrimaryKeySelective(arg);
    }

    @Override
    public List<SalePersonVolumeOfTrade> queryMySaleAccountSummary(SalePersonVolumeOfTrade spvot) {
        return dataDao.queryMySaleAccountSummary(spvot);
    }

    @Override
    public List<OrderVo> queryOrdersByOfferIdAndClienteleId(OrderVo user) {
        return dataDao.queryOrdersByOfferIdAndClienteleId(user);
    }

    @Override
    public Integer queryOrdersCountByOfferIdAndClienteleId(OrderVo user) {
        return dataDao.queryOrdersCountByOfferIdAndClienteleId(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer createTest() {
        Order order = new Order();
        Offer of = offerDao.selectByPrimaryKey(27);
        of.setCount(of.getCount() + 1);

        offerDao.updateByPrimaryKeySelective(of);
        if (true) {
            throw new RuntimeException("Exception");
        }
        order.setNo("XHP20170416-000002");
        return dataDao.insertSelective(order);
    }

    @Override
    public int queryCountBeforeDelete(Order order) {
        return dataDao.queryCountBeforeDelete(order);
    }

    @Override
    public Object addActualNumber(Order order) {
        Order order_ = dataDao.selectByPrimaryKey(order.getId());
        order.setActualNumber(Arith.add(order.getActualNumber(), order_.getActualNumber()));
        order.setDeliverNumber(Arith.sub(order_.getDeliverNumber(), order.getNumber()));
        order.setNumber(order_.getNumber());
        if (order.getActualNumber().equals(order_.getNumber())) { // 实提数量等于订单数量，订单执行完成
            order.setDeliverStatus("1");
            order.setStatus(OrderConstants.STATUS_NORMAL_END);
            int re = dataDao.updateByPrimaryKeySelective(order);
            if (re > 0) {
                SaleCommission sc = new SaleCommission();
                sc.setOrderId(order.getId().toString());
                sc.setSaleId(order_.getSaleId());
                saleCommissionService.giveCommission(sc);
                return re;
            }
        } else {
            if ((order.getNumber() > order.getActualNumber()) && (order.getActualNumber() > 0)) {
                order.setDeliverStatus("2");
            }
            int re = dataDao.updateByPrimaryKeySelective(order);
            dataDao.updateByPrimaryKeySelective(order);
        }
        return null;
    }

    /**
     * 不需要事务管理的
     *
     * @param user
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public int queryCount(OrderVo user) {
        return dataDao.queryCount(user);
    }

    @Override
    public int queryMyOrderCount(OrderVo user) {
        return dataDao.queryMyOrderCount(user);
    }

    @Override
    public int queryMySaleOrderCount(OrderVo user) {
        return dataDao.queryMySaleOrderCount(user);
    }
}
